/********************************************************/
/*	Copyright (C) 2016 Gong Li Bin		 	*/
/*	Project:	GlbLib-1.0.0			*/
/*	Author:		gong_libin			*/
/*	Date:		2016_06_01			*/
/*	File:		GlbStreamTest.cpp		*/
/********************************************************/

#include "GlbStream.h"

using namespace GlbNet;

#define	GLB_DT_URL			(char*)"/tmp/GlbUnix.sock"

void GlbStreamFunction(int iSocket)
{
	CGlbStream CStream;
	static UINT s_uiCount = 0;
	char szPacket[GLB_PACKET] = { 0 };

	CStream.GlbNetSetSocket(iSocket);
	while ((CStream.GlbStreamRead((UCHAR*)szPacket, GLB_PACKET)) > 0) {
		GLB_PRINT("Recv[%d]: %s\n", s_uiCount ++, szPacket);
	}

	return;
}

void GlbStreamTestCli()
{
	CGlbStream CStream;
	char szPacket[] = "This is a test about AF_UNIX";

	if (GLB_SUCCESS == CStream.GlbStreamConnect(GLB_DT_URL)) {
		if (CStream.GlbStreamWrite((UCHAR*)szPacket, strlen(szPacket)) > 0) {
			GLB_PRINT("Send: %s\n", szPacket);
		}
		else {
			GLB_ERROR("Failed to GlbStreamWrite\n");
		}
		CStream.GlbNetClose();
	}
	else {
		GLB_ERROR("Failed to GlbStreamConnect\n");
	}

	return;
}

void GlbStreamTestSer()
{
	CGlbStream CStream;

	unlink(GLB_DT_URL);

	if (GLB_SUCCESS == CStream.GlbStreamInit(GLB_DT_URL)) {
		CStream.GlbStreamSetFunction(GlbStreamFunction);
		CStream.GlbStreamAccept();
		CStream.GlbNetClose();
		unlink(GLB_DT_URL);
	}
	else {
		GLB_ERROR("Failed to GlbStreamInit\n");
	}

	return;
}

int main(int argc, char* argv[])
{
	if (argc < 2) {
		GLB_PRINT("Usage: %s [ser | cli]\n", argv[0]);
		return GLB_SUCCESS;
	}

	switch (strcmp(argv[1], "ser")) {
		case 0:
			GlbStreamTestSer();
			break;
		default:
			GlbStreamTestCli();
			break;
	}

	return GLB_SUCCESS;
}
